﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace Odebrecht.WpfControls
{
    public class CustomDataGrid : DataGrid
    {
        #region Fields

        public static readonly DependencyProperty ScrollVerticalOffsetProperty = 
            DependencyProperty.Register("ScrollVerticalOffset", typeof(double), typeof(CustomDataGrid), new PropertyMetadata(new PropertyChangedCallback(ScrollVerticalOffsetChangedCallback)));

        private ScrollViewer _scrollViewerElement;

        #endregion Fields

        #region Constructors

        static CustomDataGrid()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomDataGrid), new FrameworkPropertyMetadata(typeof(CustomDataGrid)));
        }

        #endregion Constructors

        #region Properties

        [Browsable(true)]
        [Category("Odebrecht")]
        [Description("A posição do eixo Y do ScrollViewer")]
        public double ScrollVerticalOffset
        {
            get { return (int)GetValue(ScrollVerticalOffsetProperty); }
            set { SetValue(ScrollVerticalOffsetProperty, value); }
        }

        #endregion Properties

        #region Methods

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _scrollViewerElement = GetTemplateChild(CustomDataGridVisualElements.ScrollViewerPART) as ScrollViewer;

            if (_scrollViewerElement != null)
            {
                _scrollViewerElement.ScrollChanged += OnScrollChanged;
            }
        }

        protected override DependencyObject GetContainerForItemOverride()
        {
            return new CustomDataGridRow();
        }

        protected virtual void ScrollVerticalOffsetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (_scrollViewerElement != null)
            {
                _scrollViewerElement.ScrollToVerticalOffset(Convert.ToDouble(e.NewValue));
            }
        }

        private static void ScrollVerticalOffsetChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var customDataGrid = sender as CustomDataGrid;
            customDataGrid.Dispatcher.Invoke(new Action(() =>
            {
                customDataGrid.ScrollVerticalOffsetChanged(sender, e);
            }));
        }

        private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            SetValue(ScrollVerticalOffsetProperty, _scrollViewerElement.VerticalOffset);
        }

        #endregion Methods
    }
}